﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Xms.Abp.BackgroundJob;

[BackgroundJobName("程序集静态执行任务", nameof(DllBackgroundJob))]
public class DllBackgroundJob : BackgroundJob<DllBackgroundJobArgs>
{
    public override async Task ExecuteAsync(DllBackgroundJobArgs args, CancellationToken cancellationToken = default)
    {
        Type type;
        if (args.DllFile.IsNullOrWhiteSpace())
        {
            type = Type.GetType(args.Type, true);
        }
        else
        {
            var fileName = Path.Combine(AppContext.BaseDirectory, args.DllFile);
            var assembly = Assembly.LoadFile(fileName);
            type = assembly.GetType(args.Type);
        }
        var method = type.GetMethod(args.Method, BindingFlags.Public | BindingFlags.Static);
        var result = method.Invoke(null, args.Args);
        if (result is Task task) await task;
    }
}
